<?php

class User_Collection extends Collection
{
	public function User_Collection()
	{
		parent::Collection("user", "uid");
	}

	public function authent($login, $mdp)
	{
		$req = "select uid, login, nom, prenom, mail from user where login = '".$login."' and mdp = sha1('".$mdp."')";
		$adapt = new SQLAdapt();
		$res = $adapt->query($req);
		if($res->rowCount() >  0)
		{
			// Construction d'un objet session
			$res = $res->fetch();
			return new UserSession($res[0], $res[1], $res[2], $res[3], $res[4]);
		}
		return null;

	}

	public function updateSessionKey($uid, $key)
	{
		$req = "update user set session_key	= '".$key."' where uid = ".$uid;
		$adapt = new SQLAdapt();
		$adapt->exec($req);
	}

	public function resetSessionKey($uid)
	{
		$req = "update user set session_key	= null where uid = ".$uid;
		$adapt = new SQLAdapt();
		$adapt->exec($req);
	}

	public function authentByID($id, $key)
	{
		$req = "select uid, login, nom, prenom, mail  from user where uid = ".$id." and session_key = '".$key."'";
		$adapt = new SQLAdapt();
		$res = $adapt->query($req);
		if($res->rowCount() >  0)
		{
			$res = $res->fetch();
			return new UserSession($res[0], $res[1], $res[2], $res[3], $res[4]);
		}
		return false;

	}

	public function getUidByMail($mail)
	{
		$req = "select uid from user where mail = '".$mail."'";
		$adapt = new SQLAdapt();
		$res = $adapt->query($req);
		if($res->rowCount() >  0)
		{
			// Construction d'un objet session
			$res = $res->fetch();
			return $res[0];
		}
		return null;
	}

	public function getUidByName($login)
	{
		$req = "select uid from user where login = '".$login."'";
		$adapt = new SQLAdapt();
		$res = $adapt->query($req);

		// Construction d'un objet session
		$res = $res->fetch();
		return $res[0];
	}

	public function getLoginByMail($mail)
	{
		$req = "select uid, login from user where mail = '".$mail."'";
		$adapt = new SQLAdapt();
		$res = $adapt->query($req);
		if($res->rowCount() >  0)
		{
			// Construction d'un objet session
			$res = $res->fetch();
			return $res[0].'¤'.$res[1];
		}
		return null;
	}

	public function isLoginExists($login)
	{
		$req = "select count(login) from user where login = '".$login."'";
		$adapt = new SQLAdapt();
		$res = $adapt->query($req);
		$res = $res->fetch();
		if($res[0] >  0)
		return true;
		else
		return false;
	}

}

?>
